package com.gk.panda.apis.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gk.panda.apis.entity.elecRail.dto.ElecRailProperties;
import com.gk.panda.apis.entity.elecRail.dto.ElecRailSaveDto;
import com.gk.panda.apis.entity.elecRail.dto.ElecRailSearchDto;
import com.gk.panda.apis.entity.elecRail.dto.HeatMapGeoJsonDto;
import com.gk.panda.apis.entity.elecRail.entity.ElecRailEntity;
import com.gk.panda.apis.log.Log;
import com.gk.panda.apis.service.CrownMoveService;
import com.gk.panda.apis.service.ElecRailService;
import com.gk.panda.commons.result.Result;
import com.gk.panda.commons.util.UserUtil;
import com.gk.panda.pojo.CrownMove;
import com.gk.panda.pojo.ElecRail;
import com.gk.panda.pojo.GeoJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/edmp/elecRail")
@Api(tags = "电子围栏热力统计")
public class ElecRailController {

    @Autowired
    private ElecRailService elecRailService;

    @Autowired
    private CrownMoveService crownMoveService;

    private static final String FILE_SUFFIX = ".xlsx";

    @ApiOperation(value = "获取热力图Geojson数据")
    @PostMapping("/heatMap")
    public Result<List<GeoJson>> getHeatMapData(@RequestBody HeatMapGeoJsonDto dto) throws Exception {
        List<GeoJson> geoJsons = elecRailService.RegionalHeatOfGIS(dto);
        return Result.ok(geoJsons);
    }

    @ApiOperation(value = "获取热力图人员移动")
    @PostMapping("/heatMap/personCount")
    public Result<List<GeoJson>> getCrowdMove(@RequestBody HeatMapGeoJsonDto dto) throws Exception {
        return Result.ok(elecRailService.getCrowdMove(dto));
    }

    @ApiOperation("新建电子围栏")
    @Log
    @PostMapping("/addElecRail")
    public Result<String> addTransect(ElecRailSaveDto dto) throws IOException {

        if (null == dto.getFile())
        {
            return Result.error(400,"电子围栏解析文件必传");
        }
        BufferedReader br = new BufferedReader(new FileReader(MultipartFileToFile(dto.getFile())));
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        String sCurrentLine;
        int count =1;
        while ((sCurrentLine = br.readLine()) != null) {
            if(count >1){
                if(!"]}".equals(sCurrentLine)){
                    sCurrentLine = sCurrentLine.replace("LineString", "Polygon");
                    sCurrentLine = sCurrentLine.replace(":[[",":[[[");
                    sCurrentLine = sCurrentLine.replace("]]},","]]]},");
                    JSONObject jsonObject = JSONUtil.parseObj(StringEscapeUtils.unescapeJava(sCurrentLine));
                    ElecRailEntity elecRailEntity = JSONUtil.toBean(jsonObject, ElecRailEntity.class);
                    JSONObject jsonObjectPro = JSONUtil.parseObj(elecRailEntity.getProperties());
                    ElecRailProperties properties = JSONUtil.toBean(jsonObjectPro, ElecRailProperties.class);

                    ElecRail elecRail = new ElecRail();
                    elecRail.setElecRailId(properties.getId());
                    elecRail.setOrgId(dto.getOrgId());
                    elecRail.setOrgName(dto.getOrgName());
                    elecRail.setGeoJson(sCurrentLine);
                    elecRail.setCreator(UserUtil.getCurrentUser());
                    elecRail.setIsCore(dto.getIsCore());
                    //存电子围栏
                    elecRailService.save(elecRail);

                    //拼接文件，返回给前端显示
                    stringBuilder.append(sCurrentLine);
                }else{
                    stringBuilder.append("]");
                }
            }
            count++;
        }
        String result = String.valueOf(stringBuilder);
        return Result.ok(result);
    }

    @ApiOperation("分页查询电子围栏信息")
    @PostMapping("/list")
    public Result<Page<ElecRail>> getElecRailList(@RequestBody ElecRailSearchDto dto) {
        return Result.ok(elecRailService.getElecRailList(dto));
    }

    @ApiOperation("查看电子围栏详情")
    @GetMapping("/getInfo/{id}")
    public Result<ElecRail> getTransectDetails(@PathVariable("id") Integer id) {
        return Result.ok(elecRailService.getById(id));
    }

    @ApiOperation("删除电子围栏信息")
    @Log
    @DeleteMapping("/remove/{id}")
    public Result<String> removeTransect(@PathVariable("id") Integer id) {
        UpdateWrapper<ElecRail> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.set("del_flag",1);
        boolean update = elecRailService.update(wrapper);
        if (update) return Result.write(200,"删除成功");
        return Result.write(201,"删除失败");
    }


    //将MultipartFile转换为File
    public File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        if (fileName == null){
            return null;
        }
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
//
//    @GetMapping("/test")
//    public void test(String time) throws Exception {
//        List<String> areaCodes = Arrays.asList("C1","C2","C3","C4","C5","C6"
//                ,"G1","G2","G3","G4","G5","G6"
//        );
//        List<CrownMoveTest> crownMoves = new ArrayList<>();
//        for (String areaCode : areaCodes) {
//            List<CrownMoveVo> crownMoveVos = elecRailService.getCrownMoveData(areaCode, time);
//            for (CrownMoveVo crownMoveVo : crownMoveVos) {
//                CrownMoveTest crownMove = new CrownMoveTest();
//                crownMove.setLot(crownMoveVo.getLON());
//                crownMove.setLat(crownMoveVo.getLAT());
//                crownMove.setQuarterNo(crownMoveVo.getQUARTER_NO());
//                crownMove.setUserId(crownMoveVo.getUSER_ID());
//                crownMove.setAreaCode(areaCode);
//                crownMoves.add(crownMove);
//            }
//        }
//        crownMoveService.saveBatch(crownMoves);
//    }
//
//    @GetMapping("/export")
//    public void export(HttpServletResponse response) {
//        List<CrownMoveTest> crownMoveTests = crownMoveService.list();
//        List<ExportCrownMoveVO> vos = ListCopyUtils.copyListProperties(crownMoveTests, ExportCrownMoveVO::new);
//        ExportParams params = new ExportParams();
//        // params.setTitle("勘界信息列表");
//        params.setSheetName("人员移动数据");
//        params.setHeight((short) 15);
//        Workbook workbook = ExcelExportUtil.exportBigExcel(params, ExportCrownMoveVO.class, vos);
//        // 生成文件
//        String downloadFileName = "人员移动数据" + FILE_SUFFIX;
//        ExcelUtils.download(downloadFileName, workbook, response);
//    }
//
//    @GetMapping("/saveCrownMoveData")
//    public void saveCrownMoveData(String time) throws Exception {
//        elecRailService.saveCrownMoveData(time);
//    }
//    @GetMapping("/test")
//    public Result<List<String>> test() {
//        List<String> result = new ArrayList<>();
//        QueryWrapper<CrownMove> wrapper = new QueryWrapper<>();
//        wrapper.gt("quarter_no", "2023021509")
//                .orderByAsc("quarter_no");
//        List<CrownMove> crownMoves = crownMoveService.list(wrapper);
//        Map<String, List<CrownMove>> map = crownMoves.stream().collect(Collectors.groupingBy(CrownMove::getUserId));
//        for (Map.Entry<String, List<CrownMove>> entry : map.entrySet()) {
//            String userId = entry.getKey();
//            List<CrownMove> crownMoveList = entry.getValue();
//            crownMoveList.sort(Comparator.comparing(CrownMove::getQuarterNo));
//            CrownMove first = crownMoveList.get(0);
//            CrownMove last = crownMoveList.get(crownMoveList.size()-1);
//            double lot = Double.parseDouble(first.getLot());
//            double lat = Double.parseDouble(first.getLat());
//            double lastLot = Double.parseDouble(last.getLot());
//            double lastLat = Double.parseDouble(last.getLat());
//            double differLot = lot - lastLot;
//            double differLat = lat - lastLat;
//            if (Math.sqrt(Math.pow((differLot) * 111, 2) + Math.pow((differLat) * 111, 2))>20) {
//                result.add(userId);
//            }
//        }
//        return Result.ok(result);
//    }
}
